package com.example.userlogin.controller;

import com.example.userlogin.entity.User;
import com.example.userlogin.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        List<User> users = userRepository.findAll();
        return ResponseEntity.ok(users);
    }

    @GetMapping("/user/{username}")
    public ResponseEntity<?> getUserByUsername(@PathVariable String username) {
        return userRepository.findByUsername(username)
                .map(user -> ResponseEntity.ok(user))
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/login-test")
    public ResponseEntity<?> testLogin(@RequestBody LoginTestRequest request) {
        try {
            // 直接查找用户
            User user = userRepository.findByUsername(request.getUsername()).orElse(null);
            if (user == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }
            
            return ResponseEntity.ok("用户存在: " + user.getUsername() + ", 邮箱: " + user.getEmail());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("错误: " + e.getMessage());
        }
    }

    public static class LoginTestRequest {
        private String username;
        private String password;
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
}